<?php
/**
 * Created by PhpStorm.
 * Script Name: FmConfig.php
 * Create: 6/4/23 11:03 AM
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace addons\fhelper\common\library;

/**
 * Save Configuration
 */
class FmConfig
{
    /**
     * 获取配置
     * @param null $id
     * @param bool $refresh
     * @return array|mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    static function getConf($id = null, $refresh = false){
        $key = fhelper_cache_key(__CLASS__ . __FUNCTION__);
        $list = cache($key);
        if(empty($list) || $refresh){
            $content = @file_get_contents(self::getConfigFile());
            $list = [];
            if($content !== FALSE) {
                $list = json_decode($content, TRUE);
            }
            $list = array_merge([
                'root_path' => dirname($_SERVER['DOCUMENT_ROOT']),
                'root_url' => '',
                "lang" => "zh-CN",
                "error_reporting" => false,
                "show_hidden" => false,
                "hide_Cols" => false,
                "theme" => "light",
                'exclude_items' => [],
                'date_format' => 'm/d/Y g:i A',
                "path_display_mode"=> "full",
                "sticky_navbar" => true,
                "ip_ruleset" => 'OFF',
                'ip_whitelist' => [
                    '127.0.0.1',    // local ipv4
                    '::1'           // local ipv6
                ],
                'ip_blacklist' => [
                    '0.0.0.0',      // non-routable meta ipv4
                    '::'            // non-routable meta ipv6
                ],
                'max_upload_size' => 5000000000, //size 5,000,000,000 bytes (~5GB)
                'upload_chunk_size' => 2000000, //// chunk size 2,000,000 bytes (~2MB)
            ], $list);
        }
        cache($key, $list);
        return  isset($list[$id]) ? $list[$id] : $list;
    }

    /**
     * save config
     * @param $post_data
     * @return bool|string
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public static function save($post_data)
    {
        try {
            $configs = array_merge(self::getConf(), $post_data);
            file_put_contents(self::getConfigFile(), json_encode($configs, JSON_UNESCAPED_UNICODE));
            self::getConf(null, true);
            return true;
        }catch (\Exception $e){
            return  $e->getMessage();
        }
    }

    static function getConfigFile(){
        $file = addon_path('fhelper', 'config.json');
        if(!file_exists($file)){
            @mkdir($file, 0755);
        }
        return $file;
    }
}
